package uk.ac.open.kmi.dyniqx.repositories;

import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import uk.ac.open.kmi.dyniqx.storages.Storage;
import uk.ac.open.kmi.dyniqx.wrappers.QueryWrapper;

import org.json.*;

public class GoogleVideoRepository implements Repository {

	private Storage storage;
	
	public Logger logger = Logger.getLogger("uk.ac.open.kmi.dyniqx.repositories.GoogleVideoRepository");
	
	public GoogleVideoRepository() {
		this.logger.debug("GoogleVideoRepository instance created.");
	}
	
	@SuppressWarnings("unchecked")
	public void performQuery(String queryString) {
		
		String baseUrl = "http://ajax.googleapis.com/ajax/services/search/video?v=1.0&q=";
		
		/* Open University proxy Settings */
 
		System.getProperties().put( "proxySet", "true" );
		System.getProperties().put( "proxyHost", "wwwcache" );
		System.getProperties().put( "proxyPort", "80" );
		System.setProperty("java.net.useSystemProxies","true");
		
	                      
		try {

			HttpClient client = new HttpClient();
			HostConfiguration hhc = client.getHostConfiguration();
			
			/* Open University proxy Settings */
 
		    hhc.setProxy("wwwcache", 80);
		    
			client.setHostConfiguration(hhc);
			
		    GetMethod method = new GetMethod(baseUrl + URLEncoder.encode(queryString, "UTF-8"));
		    
		    logger.debug(baseUrl + URLEncoder.encode(queryString, "UTF-8"));
		    
		    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
		    int statusCode = client.executeMethod(method);
		    if (statusCode != HttpStatus.SC_OK) {
		        System.err.println("Method failed: " + method.getStatusLine());
		    }

		    String line;
		    StringBuilder builder = new StringBuilder();
		    BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
		    while((line = reader.readLine()) != null) {
		    	builder.append(line);
		    }

		    JSONObject json;
		    int count = 0;
			try {
				json = new JSONObject(builder.toString());
				count = Integer.parseInt(json.getJSONObject("responseData").getJSONObject("cursor").get("estimatedResultCount").toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}	    

		    WebContext wctx = WebContextFactory.get();
	    	QueryWrapper newQuery = new QueryWrapper(queryString, "GVi", count, 0);
	    	
			this.storage.getQueryWrapper().add(newQuery);
	    	
	    	Thread t = new GoogleVideoThread(this.storage, wctx, queryString, count);
	    	t.setName("GVi" + "-" + wctx.getSession().getId() + "-" + (System.currentTimeMillis() % 1000000));
	    	t.start();
			
	    	this.storage.updateGrid();
			
		} catch (HttpException e) {
	        System.err.println("Fatal protocol violation: " + e.getMessage());
	        e.printStackTrace();
	    } catch (IOException e) {
	        System.err.println("Fatal transport error: " + e.getMessage());
	        e.printStackTrace();
	    }
	}
	
	public void setStorage(Storage storage) {
		this.storage = storage;
	}	
	
	public Storage getStorage() {
		return this.storage;
	}
}
